<template>
  <div>
    <el-row style="margin-bottom: 20px">
      <el-col :span="6">
        <el-button type="primary" @click="addCate">添加商品</el-button>
      </el-col>
    </el-row>
    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="cat_id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="cat_name" label="分类名称"> </el-table-column>
      <el-table-column prop="cat_level" label="是否有效">
        <template scope="scope">
          <i
            style="color: #39ce39"
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
          ></i>
          <i class="el-icon-error" v-else></i>
        </template>
      </el-table-column>
      <el-table-column prop="cat_pid" label="排序">
        <template scope="scope">
          <el-tag
            type="success"
            size="mini"
            effect="dark"
            v-if="scope.row.cat_level === 0"
            >一级</el-tag
          >
          <el-tag
            type="info"
            size="mini"
            effect="dark"
            v-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag
            type="danger"
            size="mini"
            effect="dark"
            v-if="scope.row.cat_level === 2"
            >三级</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="mini" type="primary" @click="Editfn(scope.row)"
            >编辑<i class="el-icon-edit"></i
          ></el-button>
          <el-button size="mini" type="danger" @click='delFn(scope.row.cat_id)'
            >删除<i class="el-icon-delete"></i
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pagenum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="queryParams.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <el-dialog
      @close="closeFn"
      title="添加商品"
      width="450px"
      :visible.sync="addFormShow"
    >
      <el-form
        ref="addform"
        v-if="addFormShow"
        label-width="100px"
        :model="form"
        :rules="addCateFormRules"
      >
        <el-form-item label="分类名称">
          <el-input v-model="form.cat_name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="父类分级">
          <el-cascader
            clearable
            style="width: 100%"
            v-model="currtentKeys"
            :options="options"
            @change="parentCateChanged"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
              checkStrictly: true,
            }"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormShow = false">取 消</el-button>
        <el-button type="primary" @click="onaddCate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCategoriesList,
  addCategories,
  editCategories,
  delCategories,
} from '../../api/categories';

export default {
  data() {
    return {
      tableData: [],
      queryParams: {
        type: 3,
        pagenum: 1,
        pagesize: 10,
      },
      total: 0,
      addFormShow: false,
      form: {
        cat_name: '',
        cat_pid: '',
        cat_level: 0,
      },
      currtentKeys: [],
      options: [],
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      isEdit: false,
      editId: null,
    };
  },
  methods: {
    // 删除
    delFn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const res = await delCategories(id);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        if (this.tableData.length === 1) {
          if (this.queryParams.pagenum === 0) {
            return;
          }
          this.queryParams.pagenum--;
        }
        this.getCategories();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        });
      });
    },
    // 打开编辑弹窗
    Editfn(row) {
      this.isEdit = true;
      this.addFormShow = true;
      this.form.cat_name = row.cat_name;
      this.editId = row.cat_id;
    },
    // 做编辑
    async onEdit() {
      const res = await editCategories(this.editId, {
        cat_name: this.form.cat_name,
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getCategories();
      this.addFormShow = false;
    },
    // 关闭弹窗
    closeFn() {
      this.addFormShow = false;
      this.form = {
        cat_name: '',
        cat_pid: '',
        cat_level: 0,
      };
      this.currtentKeys = [];
    },
    // 选中节点发生变化时
    parentCateChanged() {
      // 说明选中了节点
      if (this.currtentKeys.length > 0) {
        this.form.cat_pid = this.currtentKeys[this.currtentKeys.length - 1];
        this.form.cat_level = this.currtentKeys.length;
      } else {
        // 如果没选中  传值只传0
        this.form.cat_pid = 0;
        this.form.cat_level = 0;
      }
    },
    // 新增分类
    onaddCate() {
      this.$refs.addform.validate((validate) => {
        if (!validate) return false;
        this.isEdit ? this.onEdit() : this.onAdd();
      });
    },
    async onAdd() {
      const res = await addCategories(this.form);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getCategories();
      this.addFormShow = false;
    },
    // 获取分类列表
    async getParentList() {
      const params = {
        type: 2,
      };
      const res = await getCategoriesList(params);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.options = res.data;
    },
    addCate() {
      this.getParentList();
      this.isEdit = false;
      this.addFormShow = true;
    },
    handleCurrentChange(num) {
      this.queryParams.pagenum = num;
      this.getCategories();
    },
    handleSizeChange(num) {
      this.queryParams.pagesize = num;
      this.getCategories();
    },
    async getCategories() {
      const res = await getCategoriesList(this.queryParams);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.tableData = res.data.result;
      this.total = res.data.total;
    },
  },
  created() {
    this.getCategories();
  },
};
</script>

<style>
</style>
